#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    savename();

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_2_clicked()//登录
{
    //密码长度判定 ？>6位
    if(ui->LineEdit_2->text().length()<6){
        QMessageBox::about(this,"提示","密码长度小6位数，请重新输入！！！");
        ui->LineEdit_2->clear();
        return;
    }
    sql="SELECT * FROM user;";
    user->execute(sql,query);
    QStringList userr;
    while (query.next()==true) {
        QString name = query.value(0).toString();
        QString password = query.value(1).toString();

        qDebug()<<name<<" "<<password<<endl;
        userr.append(name);
        userr.append(password);
    }
    for (int i=0;i<userr.size();i++) {
        if(ui->user->text()==userr[i]&&ui->LineEdit_2->text()==userr[i+1]){
//            QMessageBox::about(this,"登陆成功","login succeed");
            QSettings settings("my","mysoft");
            if(ui->checkBox->isChecked()==true){
                qDebug()<<"用户选择登陆时记住密码"<<endl;
                settings.setValue("user",ui->user->text());
                settings.setValue("password",ui->LineEdit_2->text());
                settings.setValue("baocun",true);
            }else{
                settings.setValue("baocun",false);
            }
//            loaded * load =new loaded;
//            load->show();
            smarthome *home =new smarthome;
            home ->show();
            this->close();
            return;
        }
    }
//    ui->checkBox->checkState();
    QMessageBox::about(this,"登陆失败","用户或者密码错误，请重新输输入！");
    ui->LineEdit_2->clear();
    ui->user->clear();
}

void MainWindow::on_pushButton_clicked()//注册
{


    if(ui->LineEdit_2->text().length()<6){
        QMessageBox::about(this,"注册失败","密码长度小6位数，请重新输入！！！");
        ui->LineEdit_2->clear();

    }
    //创建表
    //sql="CREATE TABLE user(name varchar(256),password varchar(128)); ";
    //user->execute(sql,query);
    //将账号密码存入数据库
    else{
        sql=QString("INSERT INTO user VALUES ('%1','%2');").arg(ui->user->text()).arg(ui->LineEdit_2->text());
        user->execute(sql,query);
        QMessageBox::about(this,"注册成功","恭喜你，注册成功，快去登录吧！！！");
//        ui->LineEdit_2->clear();
//        ui->user->clear();
    }

}

void MainWindow::savename(){
//    qDebug()<<remember<<endl;
    QSettings settings("my","mysoft");
    QString username = settings.value("user").toString();
    QString password = settings.value("password").toString();
    bool isremember=settings.value("baocun").toBool();
    qDebug()<<isremember<<endl;
//    qDebug()<<user<<password<<endl;

    if(isremember==true){
        ui->user->setText(username);
        ui->LineEdit_2->setText(password);
    }
}
